package cl.scene.libbencode;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Patricio
 * Date: 23-11-2010
 * Time: 10:27:15 PM
 */
public class DictionaryType implements IContainerType {

    private SortedMap<ByteStringValue, IType> dictionary;
    private ByteStringValue tempKey;

    public DictionaryType() {
        dictionary = new TreeMap<ByteStringValue, IType>();
    }

    public IType add(ByteStringValue key, IType value) {
        return dictionary.put(key, value);
    }

    public void encodeAndWrite(OutputStream o) throws IOException {
        this.populate();
        o.write('d');
        for (ByteStringValue key : dictionary.keySet()) {
            key.encodeAndWrite(o);
            dictionary.get(key).encodeAndWrite(o);
        }
        o.write('e');
    }

    public void populate() {
    }

    public void push(IType val) {
        if (tempKey == null) {
            tempKey = (ByteStringValue) val;
        } else {
            add(tempKey, val);
        }
    }

    public void add(String key, String message) {
        add(new ByteStringValue(key), new ByteStringValue(message));
    }
}
